#! /usr/bin/python3 python3
# -*- coding: utf-8 -*-

# *************************************************************
#  Projectname @  pysm
#     Filename @  sm.py
#       Author @  Steve.ma
#  Create date @  2018/8/31
#  Description @  
# *************************************************************

from Conf import getConf,debugvalue
from Cache import CachePath
import requests
class SMClass :
    #log 日志输出  isdebug = 1 的时候 一定会输出  不验证 debugvalue
    def log(self, msg, isdebug = 0):
        if isdebug:
            print(msg)
        else :
            if debugvalue :
                print(msg)
        return

    #log 写入日志到文件
    def setLogFile(self, file, contents = None):
        file = CachePath + '/' + file
        f = open(file, 'a')
        f.writelines(contents)
        f.close()

    def curl(self, url, method = 'get', data={}, json=None, **kwargs):
        #不重定向
        kwargs['allow_redirects'] = False
        kwargs['timeout'] = 60

        if method == 'get' :
            r = self.curl_get(url, data, **kwargs)
        elif method == 'post' :
            r = self.curl_post(url, data, json, **kwargs)

        if r.status_code == requests.codes.ok :
            return r
        else :
            return

    def curl_get(self, url, params, **kwargs):
        return requests.get(url,params, **kwargs)
    def curl_post(self, url, data, json, **kwargs):
        return requests.post(url, data, json, **kwargs)

    #主SM类 构造函数，在生成对象时调用
    def __init__(self, SMInit = {}):
        return

    def getConf(self, name):
        return getConf(name)

    # 将 dict 对象转换成微信支付交互所需的 XML 格式数据
    # :param data: dict 对象
    # :return: xml 格式数据
    def dict_to_xml(self, data):
        def to_xml(data):
            xx = []
            for k, v in data.items():
                if isinstance(v, dict):
                    aa = to_xml(v)
                    s = "<{key}>{value}</{key}>".format(key=k, value=aa)
                else:
                    s = "<{key}>{value}</{key}>".format(key=k, value=v)
                xx.append(s)
            return ''.join(xx)

        return '<xml>' + to_xml(data) + '</xml>'


    def allowed_file(self, filename, ALLOWED_EXTENSIONS = set([])):
        return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS